package com.three.common.message.base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.Packet;
import com.three.protocol.BaseModule;
import com.three.tools.Utils;
import com.three.utils.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.three.protocol.CommandEnum.Command.HTTP_PROXY;

/**
 * Created by mathua on 2017/5/28.
 */
public final class HttpResponseMessage extends BaseMessage {
    private int statusCode;
    private String reasonPhrase;
    private Map<String, String> headers = new HashMap<>();
    private byte[] body;

    public HttpResponseMessage(Packet message, Connection connection) {
        super(message, connection);
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        BaseModule.HttpResponse_10 bodyData = BaseModule.HttpResponse_10.parseFrom(body);
        statusCode = bodyData.getStatusCode();
        reasonPhrase = bodyData.getReasonPhrase();
        headers = Utils.headerFromString(bodyData.getHeaders());
        this.body = StringUtils.praseFromString(bodyData.getBody());
    }

    @Override
    public byte[] encode() {
        BaseModule.HttpResponse_10.Builder builder = BaseModule.HttpResponse_10.newBuilder();
        builder.setStatusCode(statusCode);
        builder.setReasonPhrase(reasonPhrase);
        builder.setHeaders(Utils.headerToString(headers));
        builder.setBody(Arrays.toString(body));
        return builder.build().toByteArray();
    }

    public static HttpResponseMessage from(HttpRequestMessage src) {
        return new HttpResponseMessage(src.packet.response(HTTP_PROXY), src.connection);
    }

    public HttpResponseMessage setStatusCode(int statusCode) {
        this.statusCode = statusCode;
        return this;
    }

    public HttpResponseMessage setReasonPhrase(String reasonPhrase) {
        this.reasonPhrase = reasonPhrase;
        return this;
    }

    public HttpResponseMessage addHeader(String name, String value) {
        this.headers.put(name, value);
        return this;
    }

    @Override
    public String toString() {
        return "HttpResponseMessage{" +
                "statusCode=" + statusCode +
                ", reasonPhrase='" + reasonPhrase + '\'' +
                ", headers=" + headers +
                ", body=" + (body == null ? "" : body.length) +
                '}';
    }

    public String getReasonPhrase() {
        return reasonPhrase;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public byte[] getBody() {
        return body;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }
}
